package com.zbl.zblproject.core.service.impl;

import com.alipay.demo.trade.utils.DataGeneratorUtil;
import com.alipay.demo.trade.utils.ExcelUtil;
import com.google.common.base.Preconditions;
import com.zbl.zblproject.core.dto.OrderItemDTO;
import com.zbl.zblproject.core.entity.OrderItem;
import com.zbl.zblproject.core.entity.Result;
import com.zbl.zblproject.core.mapper.OrderItemMapper;
import com.zbl.zblproject.core.mapper.OrderMapper;
import com.zbl.zblproject.core.service.OrderItemService;
import com.zbl.zblproject.core.utils.ResultUtil;
import com.zbl.zblproject.erp.entity.ErpTempOrderItem;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author youlanqiang
 * @version 1.0
 * @date 2018/10/30
 */
@Service
@Transactional
public class OrderItemServiceImpl implements OrderItemService {

    @Autowired
    private OrderItemMapper orderItemMapper;

    @Autowired
    private OrderMapper orderMapper;

    @Override
    public void deleteItemById(int id) {
        OrderItem orderItem = orderItemMapper.selectById(id);
        Preconditions.checkNotNull(orderItem);
        BigDecimal price = orderItem.getShopPrice().multiply(new BigDecimal(orderItem.getGoodsNum()));
        orderMapper.updateOrderTotalSubMoney(orderItem.getOrderSn(), price);
        orderItemMapper.deleteById(id);
    }

    @Override
    public Result deleteOrderItem(String id) {
        String[] ids = id.trim().split(",");
        for(String arrayId:ids){
                List<OrderItem> orderItem = orderItemMapper.selectByIdOrderItem(arrayId);
                if (orderItem.size()==0){
                    throw new RuntimeException(arrayId+"id不存在");
                }
        }
        orderItemMapper.deleteOrderItem(id);
        return ResultUtil.success("删除"+ids.length+"条未入库订单信息成功");
    }

    @Override
    public Result updateOrderItem(OrderItem orderItem) {
        List<OrderItem> orderItem1=orderItemMapper.selectByIdOrderItem(String.valueOf(orderItem.getId()));
        if(orderItem1.size()==0){
            throw new RuntimeException(orderItem.getId()+"id不存在");
        }
        orderItemMapper.updateOrderItemNum(orderItem);
        return ResultUtil.success("修改"+orderItem.getId()+"未入库订单数量成功");
    }

    @Override
    public String exportOrderItem(HttpServletResponse response, String id) {
        try {
            List<OrderItem> orderItemList = orderItemMapper.selectByIdOrderItem(id);
            List<OrderItemDTO> OrderItemDTO = DataGeneratorUtil.generatorDTO(orderItemList);
            String fileName="orderItem";
            List<Map<String,Object>> list=createExcelRecord(OrderItemDTO);
            String columnNames[] = {"序号","商品名称","品牌名称","商品规格","供应商名称","商品编码","商品价格","商品数量","合计金额"};//列名
            String keys[] = {"count","goodsName","brandName","goodsDesc","suppliersName","shopPrice","totalMoney","goodsNum","totalMoney"};//map中的key
            ExcelUtil.downloadWorkBook(list,keys,columnNames,fileName,response);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "excel";
    }

    /**
     * 创建Excel表中的记录
     * @param
     * @return
     */
    private List<Map<String, Object>> createExcelRecord(List<OrderItemDTO> OrderItemDTO){
        List<Map<String, Object>> listmap = new ArrayList<Map<String, Object>>();
        try {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("sheetName", "未入库订单信息表");
            listmap.add(map);
            for (int j = 0; j < OrderItemDTO.size(); j++) {
                OrderItemDTO orderItemDTO=OrderItemDTO.get(j);
                Map<String, Object> mapValue = new HashMap<String, Object>();
                mapValue.put("count",orderItemDTO.getCount());
                mapValue.put("brandName",orderItemDTO.getBrandName());
                mapValue.put("goodsDesc",orderItemDTO.getGoodsDesc());
                mapValue.put("goodsName",orderItemDTO.getGoodsName());
                mapValue.put("goodsNum",orderItemDTO.getGoodsNum());
                mapValue.put("orderSn",orderItemDTO.getOrderSn());
                mapValue.put("shopPrice",orderItemDTO.getShopPrice());
                mapValue.put("suppliersName",orderItemDTO.getSuppliersName());
                mapValue.put("totalMoney",orderItemDTO.getTotalMoney());
                listmap.add(mapValue);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return listmap;
    }


    @Override
    public void uploadNumberOfItems(List<ErpTempOrderItem> items) {
        if(items.isEmpty()){
            return;
        }
        BigDecimal bigDecimal = new BigDecimal(0.0);
        String orderSn = null;
        for(ErpTempOrderItem x : items){
            OrderItem orderItem = orderItemMapper.selectById(x.getOrderItemId());
            orderSn = orderItem.getOrderSn();
            Preconditions.checkNotNull(orderItem, "没有发现订单项");
            orderItem.setGoodsNum(x.getGoodsNum());
            bigDecimal = bigDecimal.add(orderItem.getShopPrice().multiply(new BigDecimal(x.getGoodsNum())));
            orderItemMapper.updateById(orderItem);
        }
        if(orderSn != null){
            orderMapper.updateOrderTotal(orderSn, bigDecimal);
        }
    }
}
